// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

// 获取应用实例
const app = getApp();

Page({
  data: {
    motto: 'Hello World',
    userInfo: null,
    studyDays: 0,
    todayStudyTime: 0,
    todayPlans: [],
    statistics: {
      totalQuestions: 0,
      correctRate: 0,
      totalTime: 0,
      ranking: 0
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  onLoad() {
    // 检查登录状态
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      this.loadPageData();
    }
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadPageData();
    }
  },

  // 加载页面数据
  loadPageData() {
    this.getStudyStatistics();
    this.getTodayPlans();
  },

  // 获取学习统计
  getStudyStatistics() {
    app.showLoading();
    app.request({
      url: '/users/statistics',
      method: 'GET'
    }).then(res => {
      app.hideLoading();
      if (res.code === 0) {
        this.setData({
          studyDays: res.data.studyDays,
          todayStudyTime: res.data.todayStudyTime,
          statistics: {
            totalQuestions: res.data.totalQuestions,
            correctRate: res.data.correctRate,
            totalTime: (res.data.totalTime / 60).toFixed(1), // 转换为小时
            ranking: res.data.ranking
          }
        });
      }
    }).catch(() => {
      app.hideLoading();
      app.showError('获取统计数据失败');
    });
  },

  // 获取今日计划
  getTodayPlans() {
    app.request({
      url: '/memory-curve/today-tasks',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          todayPlans: res.data
        });
      }
    }).catch(() => {
      app.showError('获取今日计划失败');
    });
  },

  // 切换计划完成状态
  togglePlan(e) {
    const id = e.currentTarget.dataset.id;
    app.request({
      url: `/memory-curve/task/${id}/complete`,
      method: 'POST'
    }).then(res => {
      if (res.code === 0) {
        // 更新本地数据
        const todayPlans = this.data.todayPlans.map(plan => {
          if (plan.id === id) {
            plan.completed = !plan.completed;
          }
          return plan;
        });
        this.setData({ todayPlans });
        app.showSuccess('更新成功');
      }
    }).catch(() => {
      app.showError('更新失败');
    });
  },

  // 页面跳转方法
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  goToRealExam() {
    wx.navigateTo({
      url: '/pages/real-exam/real-exam'
    });
  },

  goToTopicPractice() {
    wx.navigateTo({
      url: '/pages/topic-practice/topic-practice'
    });
  },

  goToWrongQuestions() {
    wx.switchTab({
      url: '/pages/wrong-questions/wrong-questions'
    });
  },

  goToKnowledge() {
    wx.switchTab({
      url: '/pages/core-knowledge/core-knowledge'
    });
  },

  goToMemoryCurve() {
    wx.navigateTo({
      url: '/pages/memory-curve/memory-curve'
    });
  },

  goToEssayGuide() {
    wx.navigateTo({
      url: '/pages/essay-guide/essay-guide'
    });
  },

  viewAllPlans() {
    wx.navigateTo({
      url: '/pages/memory-curve/memory-curve'
    });
  },

  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
})
